<template>
  <div class="main">
    <p class="main_text">区域货架管理</p>
    <!-- ############################################## 查询 ############################################## -->
    <div class="top mb20 p20">
      <el-form :model="searchData">
        <div class="df fww">
          <el-form-item label="仓库名称：" style="width: 20%">
            <el-select v-model="searchData.warehouseId" filterable placeholder="选择仓库" class="mr20"
                       @change="changeSearch">
              <el-option v-for="item in WarehouseList" :key="item.warehouseId" :label="item.warehouseName"
                         :value="item.warehouseId" />
            </el-select>
          </el-form-item>
          <el-form-item label="区域名称：" style="width: 20%">
            <el-select v-model="searchData.areaName" filterable placeholder="区域名称：" class="mr20" @focus="changeArea">
              <el-option v-for="item in searchAreaArrList" :key="item.area" :value="item.area"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="货架名称：" style="width: 20%">
            <el-input v-model="searchData.keyword" placeholder="货架名称" class="mr20" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchBtn">查询</el-button>
            <el-button type="primary" plain @click="resetSearchBtn">重置</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <!-- ############################################## 表单 ############################################## -->
    <div class="cyr-flex">
      <div class="mb20">
        <el-button type="primary" @click="RucenterDialogVisible = true" v-if="roleList.write">添加货架</el-button>
      </div>
      <div class="cyr-flex-box">
        <el-table @selection-change="handleSelectionChange" :data="tableData" style="width: 100%"
                  :header-cell-style="{ background: '#f0f6fe' }" :show-overflow-tooltip="true" v-adaptive border>
          <el-table-column type="selection" width="50" />
          <el-table-column label="货架编号" prop="id" />
          <el-table-column label="所属仓库名称" prop="warehouseName" />
          <el-table-column label="区域名称" prop="area" />
          <el-table-column label="货架名称" prop="position" />
          <el-table-column label="备注" prop="note" />
          <el-table-column label="操作" fixed="right" width="100">
            <template #default="props">
              <el-button size="small" link type="primary" @click="edit(props.row)" v-if="roleList.write">编辑</el-button>
              <el-button size="small" v-if="roleList.write" link type="danger" @click="delBtn(props.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- #################################### 分页 #################################### -->
        <smartPager v-model:current-page="currentPage" v-model:page-size="pageSize" :total="Number(total)"
                    @change="handleCurrentChange" />
      </div>
    </div>
    <!-- ############################################## 蒙层 ############################################## -->
    <!-- ****************************** 添加货架 ****************************** -->
    <el-dialog v-model="RucenterDialogVisible" v-if="RucenterDialogVisible" @close="closeRucenterDialogVisible"
               width="40%" align-center>
      <template #header>
        <div class="df aic">
          <el-icon style="color: #fff" size="20">
            <Edit />
          </el-icon>&nbsp;
          <p style="color: #fff">添加货架</p>
        </div>
      </template>
      <div class="df aic jcc">
        <el-form ref="ruleFormRef" :rules="rules" :model="addFormData">
          <el-form-item label="所属仓库：" prop="warehouseId">
            <el-select v-model="addFormData.warehouseId" placeholder="选择仓库" @change="changeWareHouse">
              <el-option v-for="item in WarehouseList" :key="item.warehouseId" :label="item.warehouseName"
                         :value="item.warehouseId" />
            </el-select>
          </el-form-item>
          <el-form-item label="区域名称：" prop="area">
            <el-select style="width: 100%" v-model="addFormData.area" filterable allow-create @focus="AddchangeArea"
                       default-first-option placeholder="区域名称">
              <el-option v-for="item in areaArrList" :key="item.area" :value="item.area"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="货架名称：" prop="position">
            <el-input v-model="addFormData.position" placeholder="货架名称" />
          </el-form-item>
          <el-form-item label="货架说明：">
            <el-input v-model="addFormData.note" type="textarea" placeholder="货架说明" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="RucenterDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addData(ruleFormRef)" :loading="loading"> 添加 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- ****************************** 编辑货架 ****************************** -->
    <el-dialog v-model="centerDialogVisible" width="40%" align-center @close="closeEditDiaog">
      <template #header>
        <div class="df aic">
          <el-icon style="color: #fff" size="20">
            <Edit />
          </el-icon>&nbsp;
          <p style="color: #fff">编辑货架</p>
        </div>
      </template>
      <div class="df aic jcc">
        <el-form :model="editFormData" :rules="editRules" ref="editRulesRef">
          <el-form-item label="所属仓库：" prop="warehouseId">
            <el-select v-model="editFormData.warehouseId" placeholder="选择仓库"
                       @change="changeEditWareHouse(editFormData)">
              <el-option v-for="item in WarehouseList" :key="item.warehouseId" :label="item.warehouseName"
                         :value="item.warehouseId" />
            </el-select>
          </el-form-item>
          <el-form-item label="区域名称：" prop="area">
            <el-select style="width: 100%" v-model="editFormData.area" filterable allow-create default-first-option
                       placeholder="区域名称">
              <el-option v-for="item in areaArrList" :key="item.area" :value="item.area"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="货架名称：" prop="position">
            <el-input v-model="editFormData.position" placeholder="货架名称" />
          </el-form-item>
          <el-form-item label="货架说明：">
            <el-input v-model="editFormData.note" type="textarea" placeholder="货架说明" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="editSaveBtn(editRulesRef)" :loading="loading" v-if="roleList.write"> 保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Edit } from '@element-plus/icons-vue';
import {
  RequestUpWarehouseAreaGetlistlimit,
  RequestWarehouseList,
  RequestUpWarehouseAreaSave,
  RequestUpWarehouseAreaGetAreaInfo,
  RequestUpWarehouseAreaDeleteList,
} from '@/api/path/index.js';
import useAuthorize from '@/hooks/authorize';
let roleList = useAuthorize();
const tableData = ref<any>([
  {
    id: 99,
    name: '132',
    bh: '456',
    dz: '成都市武侯区益州大道999号',
    mj: '798',
    fzr: '王五',
    dh: '17326544352',
    status: '1',
  },
]);
const multipleSelection = ref<any>([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val;
};
const centerDialogVisible = ref<any>(false);
const RucenterDialogVisible = ref<any>(false);
/* ************************ 获取仓库下拉数据 ************************ */
const WarehouseList = ref<any>([]);
const getWarehouseList = () => {
  RequestWarehouseList().then((res: any) => {
    WarehouseList.value = res.resultObj;
  });
};
getWarehouseList();
/******************************* 获取货架信息列表 *******************************/
/* 分页器 */
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  getData();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  getData();
};
/******************************* 搜索查询 *******************************/
const searchData = ref<any>({
  warehouseId: '',
  areaName: '',
  keyword: '',
});
const total = ref<any>(1);
const currentPage = ref(1);
const pageSize = ref(10);
const getData = () => {
  RequestUpWarehouseAreaGetlistlimit({
    page: currentPage.value,
    rows: pageSize.value,
    warehouseId: searchData.value.warehouseId,
    areaName: searchData.value.areaName,
    keyword: searchData.value.keyword,
  }).then((res: any) => {
    tableData.value = res.resultObj.areas;
    total.value = res.resultObj.count;
  });
};
getData();

const searchAreaArrList = ref<any>([]);
const changeSearch = (event: any) => {
  RequestUpWarehouseAreaGetAreaInfo(event).then((res: any) => {
    searchAreaArrList.value = res.resultObj;
  });
};
const changeArea = () => {
  if (searchData.value.warehouseId == '') {
    ElMessage.error('请先选择仓库');
  }
};
const AddchangeArea = () => {
  if (addFormData.value.warehouseId == '') {
    ElMessage.error('请先选择仓库');
  }
};
const searchBtn = () => {
  getData();
};
/*********** 搜索重置 ***********/
const resetSearchBtn = () => {
  searchData.value.warehouseId = '';
  searchData.value.areaName = '';
  searchData.value.keyword = '';
  currentPage.value = 1;
  getData();
};
/******************************* 添加区域或者货架 *******************************/
const addFormData = ref({
  warehouseId: '',
  area: '',
  position: '',
  note: '',
});
const loading = ref(false);
const ruleFormRef = ref<any>()
const rules = ref<any>({
  warehouseId: [
    { required: true, message: '请选择所属仓库', trigger: 'change' },
  ],
  area: [
    { required: true, message: '请输入或选择区域', trigger: 'change' },
  ],
  position: [
    { required: true, message: '请输入货架名称', trigger: 'blur' },
  ],
})
const closeRucenterDialogVisible = () => {
  addFormData.value = {
    warehouseId: '',
    area: '',
    position: '',
    note: '',
  };
}
const addData = async (formEl: any | undefined) => {
  if (!formEl) return
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      console.log(addFormData.value);
      loading.value = true;
      RequestUpWarehouseAreaSave(addFormData.value).then((res: any) => {
        if (res.success == true) {
          ElMessage.success(res.msg);
          RucenterDialogVisible.value = false;
          loading.value = false;
          addFormData.value = {
            warehouseId: '',
            area: '',
            position: '',
            note: '',
          };
          getData();
        } else {
          ElMessage.error(res.msg);
          getData();
        }
      });
    } else {
      console.log('error submit!', fields)
    }
  })
};
const areaArrList = ref<any>([]);
const changeWareHouse = (event: any) => {
  RequestUpWarehouseAreaGetAreaInfo(event).then((res: any) => {
    areaArrList.value = res.resultObj;
  });
};
const changeEditWareHouse = (event: any) => {
  console.log('dasdsa', event);
  RequestUpWarehouseAreaGetAreaInfo(event.warehouseId).then((res: any) => {
    areaArrList.value = res.resultObj;
  });
  editFormData.value.area = '';
  editFormData.value.position = '';
};

/******************************* 编辑 *******************************/
const editFormData = ref<any>({
  warehouseId: '',
  warehouseName: '',
  area: '',
  position: '',
  note: '',
});
const closeEditDiaog = () => {
  getData();
};
const edit = (row: any) => {
  centerDialogVisible.value = true;
  editFormData.value = row;
  RequestUpWarehouseAreaGetAreaInfo(editFormData.value.warehouseId).then((res: any) => {
    areaArrList.value = res.resultObj;
  });
};
const editRulesRef = ref<any>()
const editRules = ref<any>({
  warehouseId: [
    { required: true, message: '请选择所属仓库', trigger: 'change' },
  ],
  area: [
    { required: true, message: '请输入或选择区域', trigger: 'change' },
  ],
  position: [
    { required: true, message: '请输入货架名称', trigger: 'blur' },
  ],
})
const editSaveBtn = async (formEl: any | undefined) => {
  if (!formEl) return
  await formEl.validate((valid: any, fields: any) => {
    if (valid) {
      delete editFormData.value.warehouseName;
      console.log(editFormData.value);
      RequestUpWarehouseAreaSave(editFormData.value).then((res: any) => {
        if (res.success == true) {
          ElMessage.success(res.msg);
          centerDialogVisible.value = false;
          loading.value = false;
          getData();
        } else {
          ElMessage.error(res.msg);
          getData();
        }
      });
    } else {
      console.log('error submit!', fields)
    }
  })
};
/******************************* 删除 *******************************/
const ids = ref<any>([]);
const delBtn = (row: any) => {
  ids.value.push(row.id);
  const formimgs = new FormData();
  formimgs.append('ids', ids.value);
  RequestUpWarehouseAreaDeleteList(formimgs).then((res: any) => {
    if (res.success == true) {
      ElMessage.success(res.msg);
      ids.value = [];
      getData();
    } else {
      ElMessage.error(res.msg);
      getData();
    }
  });
};
</script>

<style scoped lang="scss">
.main {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .top {
    width: 100%;
    background-color: #fff;
  }

  .content {
    width: 100%;
    background-color: #fff;
  }
}

/* 弹出框样式 */
::v-deep .el-dialog__header {
  background-color: #116cf8;
  margin-right: 0;
}

::v-deep .el-dialog__title {
  color: #fff;
}

// ::v-deep .el-icon svg {
//     color: #fff;
// }</style>
